package com.tofix.kidmall.controller;


import com.tofix.kidmall.common.CommonPage;
import com.tofix.kidmall.common.CommonResult;
import com.tofix.kidmall.entity.Role;
import com.tofix.kidmall.exception.ApiExcetion;
import com.tofix.kidmall.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.logging.Logger;

@RestController()
@Api(tags = "身份表")
@RequestMapping("/role")
public class RoleController {
    Logger logger = (Logger) LoggerFactory.getLogger((RoleController.class));

    @Autowired
    RoleService roleService;

    @ApiOperation("根据id获取身份")
    @GetMapping("/{id}")
    CommonResult<Role> getById(@PathVariable String id) {
        return CommonResult.success(roleService.getById(id).orElseGet(Role::new));
    }

    @ApiOperation("添加一个demo")
    @PostMapping("/")
    CommonResult<Role> insertDemo(@RequestBody Role role) {
        return CommonResult.success(roleService.insertRole(role));
    }

    @ApiOperation("根据id删除一个demo")
    @DeleteMapping("/{id}")
    CommonResult deleteRole(@PathVariable String id) {
        try {
            roleService.deleteRole(id);
            return CommonResult.success();
        } catch (ApiExcetion excetion) {
//            logger.debug("delete role/" + id + "error");
            CommonResult.failed("删除组件错误");
        }
        return CommonResult.failed();
    }

    @ApiOperation("更新一个role")
    @PutMapping("/{id}")
    CommonResult<Role> updaterole(@PathVariable String id, @RequestBody Role role) {
        role.setRoleId(id);
        return CommonResult.success(roleService.saveRole(role));
    }

    @ApiOperation("获取全部role")
    @GetMapping("/all")
    CommonResult<List<Role>> getAll() {
        return roleService.getAll();
    }

    /**
     * 简单的分页查询
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @ApiOperation("分页获取role")
    @GetMapping("/allbypage")
    CommonResult<CommonPage<Role>> getAllByPage(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                                @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {

        return CommonResult.success(roleService.getAllByPage(currentPage, pageSize));
    }
}
